import { useState } from 'react'
import Editor from 'react-simple-code-editor'
import { highlight, languages } from 'prismjs'
import 'prismjs/components/prism-javascript'
import 'prismjs/components/prism-typescript'
import 'prismjs/components/prism-jsx'
import 'prismjs/themes/prism.css'

interface PracticeEditorProps {
  title: string
  description: string
}

export default function PracticeEditor({ title, description }: PracticeEditorProps) {
  const [code, setCode] = useState('')
  const [output, setOutput] = useState('')
  const [error, setError] = useState('')

  const handleRunCode = () => {
    try {
      setError('')
      setOutput('')
      
      if (!code.trim()) {
        setOutput('请先编写一些代码再运行')
        return
      }
      
      // 创建一个安全的执行环境
      const sandbox = {
        console: {
          log: (...args: any[]) => {
            setOutput(prev => prev + args.map(arg => 
              typeof arg === 'object' ? JSON.stringify(arg, null, 2) : String(arg)
            ).join(' ') + '\n')
          }
        },
        useState: () => [undefined, () => {}],
        useEffect: () => {},
        useCallback: (fn: any) => fn,
        useRef: () => ({ current: null }),
        React: { useState, useEffect, useCallback, useRef }
      }

      // 执行代码
      const func = new Function('React', 'useState', 'useEffect', 'useCallback', 'useRef', 'console', code)
      func(sandbox.React, sandbox.useState, sandbox.useEffect, sandbox.useCallback, sandbox.useRef, sandbox.console)
      
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err))
    }
  }

  const handleClear = () => {
    setCode('')
    setOutput('')
    setError('')
  }

  return (
    <div className="space-y-6">
      <div>
        <h3 className="text-xl font-semibold text-gray-900 mb-2">{title}</h3>
        <p className="text-gray-600">{description}</p>
      </div>

      <div className="space-y-4">
        <div>
          <div className="flex justify-between items-center mb-3">
            <label className="text-sm font-medium text-gray-700">代码编辑器</label>
            <div className="space-x-2">
              <button
                onClick={handleRunCode}
                className="px-4 py-2 bg-green-600 text-white rounded-lg font-medium hover:bg-green-700 transition-colors text-sm"
              >
                ▶ 运行代码
              </button>
              <button
                onClick={handleClear}
                className="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg font-medium hover:bg-gray-300 transition-colors text-sm"
              >
                🗑 清空
              </button>
            </div>
          </div>
          
          <div className="border border-gray-300 rounded-lg overflow-hidden shadow-sm">
            <div className="bg-gray-800 px-4 py-2 border-b border-gray-700">
              <div className="flex items-center space-x-2">
                <div className="w-3 h-3 bg-red-500 rounded-full"></div>
                <div className="w-3 h-3 bg-yellow-500 rounded-full"></div>
                <div className="w-3 h-3 bg-green-500 rounded-full"></div>
                <span className="text-gray-300 text-sm ml-3 font-mono">practice.js</span>
              </div>
            </div>
            <Editor
              value={code}
              onValueChange={setCode}
              highlight={(code) => highlight(code, languages.javascript, 'javascript')}
              padding={20}
              className="font-mono text-sm bg-gray-900 text-gray-100 min-h-[400px] leading-relaxed"
              style={{
                fontFamily: '"Fira Code", "Monaco", "Consolas", "Liberation Mono", "Courier New", monospace',
                fontSize: 14,
                lineHeight: 1.6,
              }}
              placeholder="// 在这里编写你的代码..."
            />
          </div>
        </div>

        {(output || error) && (
          <div>
            <label className="text-sm font-medium text-gray-700 mb-2 block">输出结果</label>
            <div className="border border-gray-300 rounded-lg p-4 bg-gray-50 min-h-[120px] shadow-sm">
              {error ? (
                <div className="text-red-600 font-mono text-sm">
                  <div className="font-semibold mb-2 flex items-center">
                    <span className="mr-2">❌</span>
                    错误信息
                  </div>
                  <pre className="whitespace-pre-wrap bg-red-50 p-3 rounded border border-red-200">{error}</pre>
                </div>
              ) : (
                <div className="text-gray-800 font-mono text-sm">
                  <div className="font-semibold mb-2 flex items-center">
                    <span className="mr-2">📤</span>
                    输出结果
                  </div>
                  <pre className="whitespace-pre-wrap bg-white p-3 rounded border border-gray-200">{output}</pre>
                </div>
              )}
            </div>
          </div>
        )}
      </div>

      <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
        <h4 className="text-sm font-semibold text-blue-900 mb-2">💡 使用提示</h4>
        <ul className="text-sm text-blue-800 space-y-1">
          <li>• 在编辑器中编写你的代码</li>
          <li>• 使用 console.log() 来查看输出结果</li>
          <li>• 点击"运行代码"来执行你的代码</li>
          <li>• 点击"清空"来清除所有内容</li>
        </ul>
      </div>
    </div>
  )
} 